#include "e2d/ui/EffectsEditor.h"
#include "e2d/ui/Utils.h"


e2d::EffectsEditor::EffectsEditor()
	:fxcc::imgui::Layer("Effects Editor")
{
	LoadLastPath();
	Load();
}

void e2d::EffectsEditor::HandleFunc()
{

	auto& sg = e2d::State::Inst();

	if (sg.m_EditEffectsFlag)
	{
		OnSaveData();

		m_InstPath = sg.m_EditEffectsPath;
		Load();

		ztclog::info("load actor %s", m_InstPath.c_str());
		sg.m_EditEffectsFlag = false;
	}
}

void e2d::EffectsEditor::ViewFunc()
{
	if (!m_Inst)
	{
		return;
	}
	auto& io = ImGui::GetIO();

	if (ImGui::IsKeyReleased(ImGuiKey_S) && io.KeyCtrl)
	{
		OnSaveData();
	}

	ImGui::Text("%s", m_InstPath.c_str());
	m_Editor.EditInst<e2d::EffectsDesc>("effectsDesc", *m_Inst);

}

void e2d::EffectsEditor::Load()
{
	EffectsLoader m_Loader;

	m_Inst = m_Loader.LoadPath(m_InstPath);

	if (m_Inst)
	{
		ztclog::info("has load the file %s", m_InstPath.c_str());
	}
}

void e2d::EffectsEditor::LoadLastPath()
{
	m_InstPath = fxcc::FileUtil::ReadFileToString(CH_Path());
}

bool e2d::EffectsEditor::OnSaveData()
{
	ztclog::info("Save the actor %s", m_InstPath.c_str());

	if (!m_Inst)
	{
		return false;
	}

	fxcc::yml::Serializer serializer;
	bool flag = serializer.EncodePath<e2d::EffectsDesc>(m_InstPath, *m_Inst);
	return flag;
}

void e2d::EffectsEditor::SaveLastPath()
{
	fxcc::FileUtil::Write(CH_Path(), m_InstPath);
}

void e2d::EffectsEditor::OnDestroy()
{
	SaveLastPath();
	//OnSaveData();

}

std::string e2d::EffectsEditor::CH_Path()
{
	return ".cache/effects.imgui";
}

